package 数据结构.章节10._168_实现HashMap;

/**
 * @author 挚爱之夕
 * @date 2021/10/16 - 10 - 16 - 13:33
 * @Description: 数据结构.章节10._168_实现HashMap
 * @Version: 1.0
 */
public class HashFunction {
    /*取余法*/
    static int hashRemainder(Object x, int prime) {
        return x.hashCode() % prime;
    }

    /*加法*/
    static int additiveHash(Object key, int prime) {
        String s = key.toString();
        int hash = s.length();
        for (int i = 0; i < s.length(); i++)
            hash += s.charAt(i);
        return hash % prime;
    }

    /*位运算*/
    static int rotatingHash(String key, int prime) {
        int hash = key.length();
        for (int i = 0; i < key.length(); i++) {
            hash = (hash << 4) ^ (hash >> 28) ^ key.charAt(i);
        }
        return hash % prime;
    }

    /*乘法*/
    static long bernstein(String key, int prime) {
        long h = 0;
        long seed = 31;
        for (int i = 0; i != key.length(); i++) {
            h = seed * h + key.charAt(i);
        }
        return h % prime;
    }
}
